package chapter13.eg7;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class CountDownLatchExample {
  public static void main(String[] args) throws InterruptedException {
    CountDownLatch latch = new CountDownLatch(5);
    Service service = new Service(latch);
    Runnable task = () -> service.exec();

    for (int i = 0; i < 5; i++) {
      Thread thread = new Thread(task);
      thread.start();
    }

    System.out.println("main thread await. ");
    latch.await();
    System.out.println("main thread finishes await. ");
  }

  public static class Service {
    private CountDownLatch latch;

    public Service(CountDownLatch latch) {
      this.latch = latch;
    }

    public void exec() {
      try {
        System.out.println(Thread.currentThread().getName() + " execute task. ");
        sleep();
        System.out.println(Thread.currentThread().getName() + " finished task. ");
      } finally {
        latch.countDown();
      }
    }

    private void sleep() {
      try {
        TimeUnit.SECONDS.sleep(2);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }

}
